package com.sduept.nwld.mobile.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.manager.WaveFileManager;
import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.cim.model.extend.CfgAnalogChannel;
import com.sduept.cim.model.extend.CfgDigitalChannel;
import com.sduept.cim.model.extend.ProtectWaveFile;
import com.sduept.cim.model.extend.WaveFile;
import com.sduept.cim.model.extend.protection.cfg.ProtectCfgAnalogChannel;
import com.sduept.cim.model.extend.protection.cfg.ProtectCfgDigitalChannel;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.mobile.manager.MobileUtil;
import com.sduept.nwld.mobile.manager.wave.WaveChannelManager;
import com.sduept.stardfile.parser.model.h5Comtrade.H5DataInfo;
import com.sduept.stardfile.parser.util.H5ComtradeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 录播文件下载和波形数据获取
 *
 */
@RestController
@RequestMapping("/wave/")
public class WaveServices {
	@Autowired
	private WaveFileManager wfm;
	@Autowired
	private WaveFileManager wa;
	@Autowired
	private WaveChannelManager wcm;
	@Autowired
	private CimManager cm;
	@Autowired
	private FaultSystemProperties pros;
	
	//SQL注入检测类
	@Inject
	private MobileUtil mobileUtil;

	

	@GetMapping("/waveFileDownload/{cimFaultId}")
	public String getFaultReport(@PathVariable("cimFaultId") String cimFaultId){
			try {
				cimFaultId =mobileUtil.SQLInjectCheck(cimFaultId);
			} catch (Exception e) {
				e.printStackTrace();
				return "查找文件失败，无法下载";
			}
			/*if(!"null".equals(cimFaultId)){
				List<FaultRecord> ftList = dao.findAll(FaultRecord.class);
				boolean checkId = false;
				for(int i = 0; i < ftList.size(); i++){
					
					FaultRecord fr = ftList.get(i);
					if(fr.getId().equals(cimFaultId)){//id在数据库中有
						checkId = true;
					}
				}
				if(!checkId){
					return "";
				}
			}else{
				return "";
			}*/
		String res = "";
		if(StringUtils.isNotEmpty(cimFaultId)){
			res = wfm.downloadFaultFile(cimFaultId, null);
			if(null == res){
				res = "";
			}
		}
		return res;
	}
	
	
	
	/**
	 * 波形展示
	 * @param stationId
	 * @param lineId
	 * @param fileId
	 * @param type
	 * @param allSelector
	 * @return
	 */

	@PostMapping("/getWaveH5DataInfo4POST")
	public String getWaveH5DataInfo4POST(@RequestBody String params){
		JSONObject p = JSONObject.parseObject(params);
		String stationId = p.getString("stationId");
		String deviceId = p.getString("deviceId");
		String fileId = p.getString("fileId");
		String fileType = p.getString("fileType");
		String allSelector = p.getString("allSelector");
		try {
			/*urlp = URLDecoder.decode(params, "utf-8");
			log.info(urlp);
			JSONObject p = JSONObject.parseObject(urlp);
			String type = p.getString("type");//集中录波是1 保护录波是2
			String fileId = p.getString("fileId");
			String initParams = p.getString("initParams");
			String allSelector = p.getString("allSelector")*/;
			stationId = mobileUtil.SQLInjectCheck(stationId);
			deviceId = mobileUtil.SQLInjectCheck(deviceId);
			fileId = mobileUtil.SQLInjectCheck(fileId);
			fileType = mobileUtil.SQLInjectCheck(fileType);
			allSelector = mobileUtil.SQLInjectCheck(allSelector);
			JSONObject initParams=new JSONObject();
		    initParams.put("stationId",stationId);
		    initParams.put("lineId",deviceId);
			int[] chnSelectInfoArray = null;
			if(StringUtils.isNotEmpty(allSelector)){
				List<Integer> chnSelectInfoList = JSONArray.parseArray(allSelector, Integer.class);
				if(chnSelectInfoList.size() > 0){
					chnSelectInfoArray = new int[chnSelectInfoList.size()];
					for(int i=0;i<chnSelectInfoArray.length;i++) {
						if(chnSelectInfoList.get(i) != null) {
							chnSelectInfoArray[i] = chnSelectInfoList.get(i).intValue();
						}
					}
				}
			}
			//首先判断是哪种录波。判断完之后，调用不同录波的方法，拿到数据
			if(StringUtils.isEmpty(fileType)){
				fileType = getWaveType(fileId);
			}else {
				fileType=getWaveTypeByType(fileType);
			}
			H5DataInfo info = null;
			switch (fileType) {
			case "1":
				info = getBxWaveH5DataInfo(fileId,chnSelectInfoArray,initParams.toString());
				break;
			case "2":
				info = getProtectWaveH5DataInfo(fileId,chnSelectInfoArray);
				break;
			default:
				break;
			}
			return JSONObject.toJSONString(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	private String getWaveType(String fileId){
		WaveFile file = wa.getWaveFileById(fileId);
		if(file == null){
			return "2";
		}else{
			return "1";
		}
	}
	private String getWaveTypeByType(String fileType) {
		if(fileType.contains("保护")) {
			return "2";
		}else{
			return "1";
		}
	}
	/**
	 * 得到集中录波的文件信息
	 * @param fileId
	 * @param stationId
	 * @param lineId
	 * @param selectInfo
	 * @return
	 */
	private H5DataInfo getBxWaveH5DataInfo(String fileId,int[] selectInfo,String initParams){
		WaveFile file = wa.getWaveFileById(fileId);
		if(file != null){
			String filePath = pros.getWaveFilePath()+file.getPath();
			File f = new File(filePath+".cfg");
			if(f.exists()){
				int[] initSelectAnalogs = null;
				int[] initSelectDigitals = null;
				if(selectInfo == null && StringUtils.isNotEmpty(initParams)){//当selectInfo是null的时候，去拿默认值
					JSONObject p = JSONObject.parseObject(initParams);
					String stationId = p.getString("stationId");
					String lineId = p.getString("lineId");
					if(StringUtils.isNotEmpty(lineId) && StringUtils.isNotEmpty(stationId)){
						initSelectAnalogs = getBxWaveInitSelectAnalogs(lineId,stationId,file.getEquipId());
						initSelectDigitals = getBxWaveInitSelectDigitals(lineId,stationId,file.getEquipId());
					}
				}
				H5DataInfo info = H5ComtradeUtil.getComtradeData(filePath, selectInfo, initSelectAnalogs, initSelectDigitals, null, true, 2048*1024);
				return info;
			}
		}
		return null;
	}
	/**
	 * 得到保护录波的文件信息
	 * @param fileId
	 * @param stationId
	 * @param lineId
	 * @param selectInfo
	 * @return
	 */
	private H5DataInfo getProtectWaveH5DataInfo(String fileId,int[] selectInfo ){
		ProtectWaveFile file = wa.getProtectWaveFile(fileId);
		if(file != null){
			String filePath = pros.getWaveFilePath()+file.getPath();
			File f = new File(filePath+".cfg");
			if(f.exists()){
				int[] initSelectAnalogs = null;
				int[] initSelectDigitals = null;
				if(selectInfo == null){//当selectInfo是null的时候，去拿默认值
					initSelectAnalogs = getProtectWaveInitSelectAnalogs(file.getEquipId());
					initSelectDigitals = getProtectWaveInitSelectDigitals(file.getEquipId());
				}
				H5DataInfo info = H5ComtradeUtil.getComtradeData(filePath, selectInfo, initSelectAnalogs, initSelectDigitals, null, true, 2048*1024);
				return info;
			}
		}
		return null;
	}
	/**
	 * 集中录波的模拟量通道号。包括线路和变电站对应的电压电流模拟量通道号，以及开关对应的电流模拟量通道号。
	 * @param lineId
	 * @param stationId
	 * @param waveFile
	 * @return
	 */
	private int[] getBxWaveInitSelectAnalogs(String eid,String stationId,String waveEquipId){
		//waveFile != null
		List<Integer> channelNumbers = new ArrayList<Integer>();
		//根据线路找到对应的开关
		List<Breaker> breakers = cm.getBreakersById(eid, stationId);
		//根据线路找（模拟通道）表中的线路关联的电压、电流通道号，根据开关找到 的电流通道号
		List<CfgAnalogChannel> list1 = wcm.listChannelsByConditions(stationId, eid, "V",waveEquipId);
		for(CfgAnalogChannel channel:list1){
			channelNumbers.add(channel.getNo());
		}
		List<CfgAnalogChannel> list2 = wcm.listChannelsByConditions(stationId, eid, "A",waveEquipId);
		for(CfgAnalogChannel channel:list2){
			channelNumbers.add(channel.getNo());
		}
		for(Breaker b:breakers){
			List<CfgAnalogChannel> aList= wcm.listChannelsByConditions(stationId, b.getId(), "A",waveEquipId);
			for(CfgAnalogChannel channel:aList){
				channelNumbers.add(channel.getNo());
			}
		}
		int[] numbers = new int[channelNumbers.size()];
		for(int i=0;i<channelNumbers.size();i++){
			numbers[i] = channelNumbers.get(i).intValue();
		}
		return numbers;
	}
	/**
	 * 集中录波的模拟量通道号。
	 * 包括线路和变电站对应的电压电流模拟量通道号，以及开关对应的电流模拟量通道号。
	 * @param lineId
	 * @param stationId
	 * @param waveFile
	 * @return
	 */
	private int[] getBxWaveInitSelectDigitals(String eid,String stationId,String waveEquipId){
		List<Integer> digNumbers=new ArrayList<Integer>();
	
		List<Breaker> breakers = cm.getBreakersById(eid, stationId);
		for(Breaker b:breakers){
			List<CfgDigitalChannel> list = wcm.listCfgDigitalChannelsByEquipementId(b.getId());
			for(CfgDigitalChannel channel:list){
				digNumbers.add(channel.getNo());
			}
		}
		List<ProtectionEquipment> listEquipments = cm.listsByStationIdAndProtectedId(stationId,eid);
		for(ProtectionEquipment pro:listEquipments){
			List<CfgDigitalChannel> channels = wcm.listDiChannelsByConditions(stationId, pro.getId(),waveEquipId);
			for(CfgDigitalChannel channel:channels){
				digNumbers.add(channel.getNo());
			}
		}
		int[] numbers = new int[digNumbers.size()];
		for(int i=0;i<digNumbers.size();i++){
			numbers[i] = digNumbers.get(i).intValue();
		}
		return numbers;
	}
	/**
	 * 根据保护id，拿到保护对应的模拟量通道号
	 * @param ptId
	 * @return
	 */
	private int[] getProtectWaveInitSelectAnalogs(String ptId){
		List<ProtectCfgAnalogChannel> list = wcm.listProtectCfgAnalogChannelsByPtId(ptId);
		List<Integer> analogNumbers = new ArrayList<>();
		for(int i=0;i<list.size();i++){
			if(StringUtils.isNotEmpty(list.get(i).getEquipmentId())){
				analogNumbers.add(list.get(i).getNo());
			}
		}
		int[] numbers = new int[analogNumbers.size()];
		for(int i=0;i<analogNumbers.size();i++){
			numbers[i] = analogNumbers.get(i).intValue();
		}
		return numbers;
	}
	/**
	 * 根据保护id，拿到保护对应的数字量通道号
	 * @param ptId
	 * @return
	 */
	private int[] getProtectWaveInitSelectDigitals(String ptId){
		List<ProtectCfgDigitalChannel> list = wcm.listProtectCfgDigitalChannelsByPtId(ptId);
		List<Integer> digitalNumbers = new ArrayList<>();
		for(int i=0;i<list.size();i++){
			if(StringUtils.isNotEmpty(list.get(i).getEquipmentId())){
				digitalNumbers.add(list.get(i).getNo());
			}
		}
		int[] numbers = new int[digitalNumbers.size()];
		for(int i=0;i<digitalNumbers.size();i++){
			numbers[i] = digitalNumbers.get(i).intValue();
		}
		return numbers;
	}
}
